<?php
namespace app\admin\controller;
use app\admin\controller\BaseAdmin;
use think\Db;
class Menu extends BaseAdmin{
    public function index(){
        $mid = (int)input('get.mid');
        $menus = $this->db->table('admin_menus')->where(array('pid'=>$mid))->order('ord', 'desc')->lists();
//        exit(dump($menus));
        // 返回上级菜单
        $backid = 0;
        if($mid > 0){
            $parent = $this->db->table('admin_menus')->where(array('mid'=>$mid))->item();
            $backid = $parent['pid'];
        }
//        exit(dump($menus));
//        dump($menus);
        $this->assign('mid',$mid);
        $this->assign('backid',$backid);
        $this->assign('menus',$menus);
        return $this->fetch();
    }
    public function save(){
        $pid = (int)input('post.id');
        $ords = input('post.ords/a');//tp接受数据如果是数组需要加标记/a，否则以字符串处理;ords===pid
        $titles = input('post.titles/a');
        $controllers = input('post.controller/a');
        $methods = input('post.method/a');
        $ishiddens = input('post.ishidden/a');
        $status = input('post.status/a');
        foreach ($ords as $key => $value){
            // 新增
            $data['pid'] = $pid;
            $data['ord'] = $value;
            $data['title'] = $titles[$key];
            $data['controller'] = $controllers[$key];
            $data['method'] = $methods[$key];
            $data['ishidden'] = isset($ishiddens[$key]) ? 0 : 1;
            $data['status'] = isset($status[$key]) ? 0 : 1;
            if($key==0 && $data['title']){
                if(!$data['ord']){
                    $data['ord'] = '999';
                }
                $res = $this->db->table('admin_menus')->insert($data);
                //dump($res);dump($data);die;
            }
            if($key > 0){
                if($data['title']=='' && $data['controller']=='' && $data['method'] == ''){
                    // 删除
                    $this->db->table('admin_menus')->where(array('mid'=>$key))->delete();
                    $this->db->table('admin_menus')->where(array('pid'=>$key))->delete();
                }else{
                    // 修改
                    $this->db->table('admin_menus')->where(array('mid'=>$key))->update($data);
                }
            }
        };
        exit(json_encode(array('code'=>0,'msg'=>'保存成功')));
    }
}